#include <QtGui>
#include "FileSortFilterModel.h"
#include "FileNode.h"
/*---------------------------------------------------------------------------*/
FileSortFilterModel::FileSortFilterModel(QObject *parent) : QSortFilterProxyModel(parent)
{
	QStandardItemModel *model = new QStandardItemModel(0, 6, parent);
	
	model->setHeaderData(COLUMN_HIDDEN, Qt::Horizontal, QObject::tr("Hidden"));
	
	model->setHeaderData(COLUMN_ICON, Qt::Horizontal, QObject::tr(""));
	model->setHeaderData(COLUMN_FILENAME, Qt::Horizontal, QObject::tr("Filename"));
	model->setHeaderData(COLUMN_EXT, Qt::Horizontal, QObject::tr("Ext"));
	model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, QObject::tr("Size"));
    model->setHeaderData(COLUMN_TYPE, Qt::Horizontal, QObject::tr("Type"));
    
   

	setSourceModel(model);
}
/*---------------------------------------------------------------------------*/
bool FileSortFilterModel::filterAcceptsRow(int sourceRow,  const QModelIndex &sourceParent) const
{
	return true;
}
/*---------------------------------------------------------------------------*/
bool FileSortFilterModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{

	
	
	FileNode *fn1 = reinterpret_cast<FileNode*>(sourceModel()->data( sourceModel()->index(left.row(), 0) ).toUInt());
	FileNode *fn2 = reinterpret_cast<FileNode*>(sourceModel()->data( sourceModel()->index(right.row(), 0) ).toUInt());
		
	int col = left.column();
	
	
	

	if( fn1 != NULL && fn2 != NULL )
	{
	
		// ".." on top
		if( fn2->getParent() != NULL && fn1 == fn2->getParent()->getParent() )
		{
			return !sortOrder();
		}
		else if( fn1->getParent() != NULL &&  fn2 == fn1->getParent()->getParent() )
		{
			return sortOrder();
		}	
		
		// folders first
		if( fn1->isFolder() && !fn2->isFolder() ) return 1;
		if( fn2->isFolder() && !fn1->isFolder()  ) return 0;		
	
	}
	

	
				
	switch( col )
	{
		// name column
		case COLUMN_FILENAME:
		{
			return  fn1->getName() < fn2->getName() ;
		}
		break;
		
		// ext column
		case COLUMN_EXT:
		{
			return  fn1->getExtension() < fn2->getExtension() ;
		}
		break;
		
		// size column
		case COLUMN_SIZE:
		{
			return  fn1->getSize() < fn2->getSize() ;
		}
		break;	
			
		// type column
		case COLUMN_TYPE:
		{
			return  fn1->getType() < fn2->getType() ;
		}
		break;
	}
	
	return 0;
	
}
/*---------------------------------------------------------------------------*/
Qt::ItemFlags FileSortFilterModel::flags(const QModelIndex& index) const
{
	// uneditable items!
	return (QSortFilterProxyModel::flags(index) & ~Qt::ItemIsEditable);
}
/*---------------------------------------------------------------------------*/
bool FileSortFilterModel::insertRow ( int row, const QModelIndex & parent )
{
	return QAbstractItemModel::insertRow(row,parent) ;
}
/*---------------------------------------------------------------------------*/


